import { EventSourcePolyfill } from 'event-source-polyfill'
import router from '@/router'
import { solarPowerSystem } from '@/common/projectAlias'
export default class SSEClient {
  constructor(
    url,
    options = {
      headers: {
        'X-Tbd-Token': sessionStorage.aiUserMessage ? JSON.parse(sessionStorage.aiUserMessage).aiSessionId : '',
        menuCode: router.currentRoute.value?.meta?.menuCode ?? '',
        projectAlias: solarPowerSystem
      }
    }
  ) {
    this.url = url
    this.options = options
    this.eventSource = null
    this.eventHandlers = {}
  }

  // 启动 SSE 连接
  start() {
    if (this.eventSource) {
      console.warn('SSE connection already established.')
      return
    }

    this.eventSource = new EventSourcePolyfill(this.url, this.options)

    this.eventSource.onopen = event => {
      this.handleEvent('open', event)
    }

    this.eventSource.onerror = event => {
      this.handleEvent('error', event)
      // 处理连接错误（例如，自动重连机制）
      if (event.target.readyState === EventSource.CLOSED) {
        console.warn('SSE connection closed. Attempting to reconnect...')
        this.reconnect()
      }
    }

    this.eventSource.onmessage = event => {
      this.handleEvent('message', event)
    }
  }

  // 处理指定类型的事件
  handleEvent(eventType, event) {
    if (this.eventHandlers[eventType]) {
      this.eventHandlers[eventType](event)
    }
  }

  // 设置事件处理器
  on(eventType, handler) {
    this.eventHandlers[eventType] = handler
  }

  // 关闭 SSE 连接
  stop() {
    if (this.eventSource) {
      console.log('断开连接')
      this.eventSource.close()
      this.eventSource = null
    }
  }

  // 重连机制
  reconnect() {
    this.stop()
    setTimeout(() => this.start(), 3000) // 3秒后重连
  }
}
